package com.xlinur.android.moviecatalog;
//TODO написать About
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import com.xlinur.android.moviecatalog.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.text.SpannableString;
import android.util.Xml;
import android.widget.TextView;
import android.widget.Toast;

public class Preferences extends PreferenceActivity {
	private static final int ALERT_DEFAULT = 0;
	private static final int ALERT_CLEARDB = 1;
	private static final int ALERT_ABOUT = 2;
	private static final String ENCODING = "UTF-8";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
		Preference prefSave = (Preference) findPreference("prefSave");
		prefSave.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				savePreferences();
				return false;
			}
		});
		Preference prefLoad = (Preference) findPreference("prefLoad");
		prefLoad.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				loadPreferences();
				return false;
			}
		});
		Preference prefDefault = (Preference) findPreference("prefDefault");
		prefDefault
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {
					public boolean onPreferenceClick(Preference preference) {
						showDialog(ALERT_DEFAULT);
						return false;
					}
				});
		Preference prefClearDB = (Preference) findPreference("prefClearDB");
		prefClearDB
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {
					public boolean onPreferenceClick(Preference preference) {
						showDialog(ALERT_CLEARDB);
						return false;
					}
				});
		Preference prefAbout = (Preference) findPreference("prefAbout");
		prefAbout.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				showDialog(ALERT_ABOUT);
				return false;
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ALERT_DEFAULT:
			return new AlertDialog.Builder(this)
					.setMessage(R.string.message_confirm_pref_default)
					.setPositiveButton(R.string.button_yes,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									clearAllPreferences();
									Toast.makeText(getApplicationContext(),
											R.string.pref_default_success,
											MovieCatalog.MESSAGE_TIME).show();
								}
							})
					.setNegativeButton(R.string.button_no,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).create();
		case ALERT_CLEARDB:
			return new AlertDialog.Builder(this)
					.setMessage(R.string.message_confirm_pref_cleardb)
					.setPositiveButton(R.string.button_yes,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									MovieCatalog.db.drop();
									MovieCatalog.db.create();
									Toast.makeText(getApplicationContext(),
											R.string.pref_cleardb_success,
											MovieCatalog.MESSAGE_TIME).show();
								}
							})
					.setNegativeButton(R.string.button_no,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).create();
		case ALERT_ABOUT:
			String versionInfo = "";
			try {
				PackageInfo pInfo = this.getPackageManager().getPackageInfo(
						this.getPackageName(), PackageManager.GET_META_DATA);
				versionInfo = pInfo.versionName;
			} catch (NameNotFoundException e) {
			}

			String aboutTitle = this.getString(R.string.app_name);
			String versionString = this.getString(R.string.pref_version)+" "+versionInfo;
			String aboutText = this.getString(R.string.pref_about_text);
			final TextView message = new TextView(this);
			final SpannableString s = new SpannableString(aboutText);
			message.setPadding(5, 5, 5, 5);
			message.setText(versionString + "\n\n" + s);
			return new AlertDialog.Builder(this)
					.setTitle(aboutTitle)
					.setView(message).create();
		default:
			break;
		}
		return null;
	}

	private void clearAllPreferences() {
		PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit()
				.clear().commit();
		finish();
		startActivity(getIntent());
	}

	private void savePreferences() {
		boolean flag = false;
		File xmlFile = new File(Environment.getExternalStorageDirectory()
				+ File.separator + MovieCatalog.PREFS_FILE);
		try {
			xmlFile.createNewFile();
			flag = true;
		} catch (IOException e) {
			flag = false;
		}
		FileOutputStream fileOS = null;
		if (flag) {
			try {
				fileOS = new FileOutputStream(xmlFile);
				flag = true;
			} catch (FileNotFoundException e) {
				flag = false;
			}
		}
		if (flag) {
			XmlSerializer serializer = Xml.newSerializer();
			try {
				serializer.setOutput(fileOS, ENCODING);
				serializer.startDocument(ENCODING, Boolean.valueOf(true));
				serializer.startTag(null, "root");

				Set<?> prefs = PreferenceManager
						.getDefaultSharedPreferences(getBaseContext()).getAll()
						.entrySet();
				Iterator<?> i = prefs.iterator();
				while (i.hasNext()) {
					Entry<?, ?> el = (Entry<?, ?>) i.next();
					serializer.startTag(null, (String) el.getKey());
					serializer.text(el.getValue().toString());
					serializer.endTag(null, (String) el.getKey());
				}

				serializer.endTag(null, "root");
				serializer.endDocument();
				serializer.flush();
				fileOS.close();
				flag = true;
			} catch (IllegalArgumentException e) {
				flag = false;
			} catch (IllegalStateException e) {
				flag = false;
			} catch (IOException e) {
				flag = false;
			}
		}
		if (flag) {
			Toast.makeText(getApplicationContext(), R.string.pref_save_success,
					MovieCatalog.MESSAGE_TIME).show();
		} else {
			Toast.makeText(getApplicationContext(), R.string.pref_save_fail,
					MovieCatalog.MESSAGE_TIME).show();
		}
	}

	private void loadPreferences() {
		boolean flag = false;
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		SharedPreferences.Editor editor = prefs.edit();
		File xmlFile = new File(Environment.getExternalStorageDirectory()
				+ File.separator + MovieCatalog.PREFS_FILE);
		FileInputStream fileIS = null;
		try {
			fileIS = new FileInputStream(xmlFile);
			flag = true;
		} catch (FileNotFoundException e) {
			flag = false;
		}
		if (flag) {
			XmlPullParserFactory factory;
			try {
				String tagName = null;
				factory = XmlPullParserFactory.newInstance();
				factory.setNamespaceAware(true);
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(fileIS, ENCODING);
				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT) {
					if (eventType == XmlPullParser.START_TAG) {
						tagName = parser.getName();
					} else if (eventType == XmlPullParser.END_TAG) {
						tagName = null;
					} else if (eventType == XmlPullParser.TEXT) {
						if (tagName != null) {
							editor.putString(tagName, parser.getText());
						}
						tagName = null;
					}
					eventType = parser.next();
				}
				flag = true;
			} catch (XmlPullParserException e) {
				flag = false;
			} catch (IOException e) {
				flag = false;
			}

		}
		if (flag) {
			editor.commit();
			finish();
			startActivity(getIntent());
			Toast.makeText(getApplicationContext(), R.string.pref_load_success,
					MovieCatalog.MESSAGE_TIME).show();
		} else {
			Toast.makeText(getApplicationContext(), R.string.pref_load_fail,
					MovieCatalog.MESSAGE_TIME).show();
		}
	}
}